package ipartek.mpa.servlet;

import ipartek.hobetuz.bean.Alumno;
import ipartek.hobetuz.excepciones.AlumnoException;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class CrearAlumnoServlet
 */
public class CrearAlumnoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CrearAlumnoServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dispatcher = null;
		HttpSession session = request.getSession(true);
		String strDispatcher = null;
		if (session.getAttribute("user") != null){
			String dni = request.getParameter("dni");
			String nombre = request.getParameter("nombre");
			String apellido1 = request.getParameter("apellido1");
			String apellido2 = request.getParameter("apellido2");
			String edad = request.getParameter("edad");
			String email = request.getParameter("email");
			if(dni != null || nombre != null || apellido1 != null || apellido2 != null || edad != null
					|| email != null){
				try {
					Alumno alumno = new Alumno(nombre, apellido1, apellido2, Integer.valueOf(edad), "", dni, "", 'S', email);
					request.setAttribute("alumno", alumno);				
					request.setAttribute("msg", "Formulario completado correctamente !!!");
					strDispatcher = "mostrarAlumno.jsp";					
				} catch (NumberFormatException e) {
					request.setAttribute("msg", e.getMessage());
					e.printStackTrace();
					strDispatcher = "insertarAlumno.jsp"; 
				} catch (AlumnoException e) {
					request.setAttribute("msg", e.getMensaje());
					e.printStackTrace();
					strDispatcher = "insertarAlumno.jsp";
				} finally {					
					dispatcher = request.getRequestDispatcher(strDispatcher);
				}
			}
			else{
				if(request.getRequestURI().equals("/MiPrimertaAppWeb/insertarAlumno")){
					request.setAttribute("msg", "Debes completar todos los campos del formulario !!!");					
				}
				dispatcher = request.getRequestDispatcher("insertarAlumno.jsp");
			}
		}
		else{
			request.setAttribute("msg", "Te has saltado la seguridad de la aplicación!!!");
			dispatcher = request.getRequestDispatcher("login.jsp");			
		}		
		dispatcher.forward(request, response);
	}

}
